<template>
	<view class="content">
		<view class="container">
			<uni-search-bar @confirm="skip" :focus="true" v-model="search.address" @input="inputChange" cancelButton="auto" @cancel="cancel" @clear="clear" placeholder="请输入小区名或地址">
			</uni-search-bar>
		</view>
		<scroll-view scroll-y="true" class="conL">
			<view v-if="dataList.length">
				<view class="list" v-for="(item,index) in dataList" :key="index" @click="skipNext(item)">{{item.name}}</view>
			</view>
			<empty v-else></empty>
		</scroll-view>
	</view>
</template>

<script setup>
	import { reactive, ref } from "vue";
	import { onLoad } from "@dcloudio/uni-app"
	import { locationEntryPrompt } from '@/common/API/room'
	const search = reactive({
		address: ''
	})

	// 清空按钮
	const clear = () => {
		search.address = ''
		reset()
		// getData()
	}
	// 重置数据 
	const reset = () => {
		dataList.value = []
	}

	// 输入框输入
	const inputChange = (val) => {
		reset()
		let time = null; //time用来控制事件的触发
		if (time !== null) {
			clearTimeout(time);
		}
		time = setTimeout(() => {
			getData()
		}, 500)
	}

	// 获取数据
	const dataList = ref([])
	const getData = async () => {
		uni.showLoading({
			title: '加载中...'
		});
		try {
			const data = await locationEntryPrompt({
				address: search.address,
				coordType: 'gcj02ll'
			})
			dataList.value = data || []
		} catch (e) {
			console.log(e);
		} finally {
			uni.hideLoading()
		}
	}


	// 键盘确认跳转
	const skip = () => {
		// uni.redirectTo({
		// 	url: `/pages/searchRoom/commutingSearch?search=${search.address}`
		// })
		getData()
	}

	const skipNext = (item) => {
		uni.redirectTo({
			url: `/pages/searchRoom/commutingSearch?search=${item.name}&address=${item.address}&lat=${item.location.lat}&lng=${item.location.lng}`
		})
	}

	// 取消按钮
	const cancel = () => {
		// uni.navigateBack()
		uni.redirectTo({
			url: '/pages/searchRoom/commutingSearch'
		})
	}

	onLoad((options) => {
		reset()
		if(options.search){
			search.address = options.search
			getData()
		}
	})
</script>

<style scoped lang="scss">
	.content {
		width: 100%;
		height: 100vh;
		display: flex;
		flex-direction: column;
	}
	.conL {
		flex: 1;
		overflow-y: auto;
		background-color: #fff;
		padding: 0 32rpx;
		box-sizing: border-box;
		.list {
			width: 100%;
			padding: 20rpx 0;
			font-size: 28rpx;
			border-bottom: 1rpx solid #E5E5E5;
			&:last-child{
				border: none;
			}
		}
	}
	.container {
		background-color: #fff;
		padding: 20rpx 32rpx 24rpx;
		::v-deep .uni-searchbar{
			padding: 0;
		}
	}
</style>